<template>
  <div class="chess-game">
    <h2>象棋游戏</h2>
    <div class="chessboard">
      <div v-for="(row, rowIndex) in board" :key="rowIndex" class="chess-row">
        <div
          v-for="(piece, colIndex) in row"
          :key="colIndex"
          class="chess-cell"
          :class="{ 'dark': isDark(rowIndex, colIndex) }"
          @click="handleCellClick(rowIndex, colIndex)"
        >
          <span v-if="piece" class="piece" :class="getPieceClass(piece)">
            {{ getPieceSymbol(piece) }}
          </span>
        </div>
      </div>
    </div>
    <div class="status">
      <p>当前玩家: {{ currentPlayer }}</p>
      <p v-if="selectedPiece">选中棋子: {{ getPieceSymbol(selectedPiece.piece) }} at ({{ selectedPiece.row }}, {{ selectedPiece.col }})</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChessGame',
  data() {
    return {
      // 8x8 board, null represents an empty square
      // Piece notation: 'r' rook, 'n' knight, 'b' bishop, 'q' queen, 'k' king, 'p' pawn
      // Uppercase for white, lowercase for black
      board: [
        ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
        ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
        [null, null, null, null, null, null, null, null],
        [null, null, null, null, null, null, null, null],
        [null, null, null, null, null, null, null, null],
        [null, null, null, null, null, null, null, null],
        ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
        ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
      ],
      currentPlayer: 'white', // 'white' or 'black'
      selectedPiece: null, // { piece: 'P', row: 6, col: 0 }
      // Add more state as needed: move history, captured pieces, check status etc.
    };
  },
  methods: {
    isDark(row, col) {
      return (row + col) % 2 !== 0;
    },
    getPieceSymbol(piece) {
      const symbols = {
        'r': '♜', 'n': '♞', 'b': '♝', 'q': '♛', 'k': '♚', 'p': '♟',
        'R': '♖', 'N': '♘', 'B': '♗', 'Q': '♕', 'K': '♔', 'P': '♙',
      };
      return symbols[piece] || '';
    },
    getPieceClass(piece) {
      if (!piece) return '';
      return piece === piece.toUpperCase() ? 'white-piece' : 'black-piece';
    },
    handleCellClick(row, col) {
      const clickedPiece = this.board[row][col];

      // Remove highlight from previously selected cell
      if (this.selectedPiece) {
        const prevRow = this.selectedPiece.row;
        const prevCol = this.selectedPiece.col;
        // Remove the class using DOM manipulation (requires refs) or a computed property
        // For simplicity, I'm skipping the actual DOM manipulation here
      }

      if (this.selectedPiece) {
        // Attempt to move the selected piece
        const targetPiece = clickedPiece;
        const source = this.selectedPiece;

        // Basic validation: Can't capture own piece (implement proper move validation later)
        if (targetPiece && this.getPieceClass(targetPiece) === this.getPieceClass(source.piece)) {
           console.log("Cannot capture own piece.");
           this.selectedPiece = null; // Deselect
           return;
        }

        // TODO: Implement actual chess move validation logic here
        if (!this.isValidMove(source.piece, source.row, source.col, row, col)) {
          console.log("Invalid move!");
          this.selectedPiece = null;
          return;
        }

        console.log(`Moving ${source.piece} from (${source.row}, ${source.col}) to (${row}, ${col})`);

        // Make the move
        this.board[row][col] = source.piece;
        this.board[source.row][source.col] = null;

        // Update board reactivity (Vue 3 handles this automatically, Vue 2 might need Vue.set or this.$set)
        // For simplicity, assuming Vue 3 or adequate reactivity setup

        this.selectedPiece = null; // Deselect after move
        this.currentPlayer = this.currentPlayer === 'white' ? 'black' : 'white'; // Switch turn

      } else if (clickedPiece) {
        // Select a piece if it belongs to the current player
        const pieceColor = clickedPiece === clickedPiece.toUpperCase() ? 'white' : 'black';
        if (pieceColor === this.currentPlayer) {
          this.selectedPiece = { piece: clickedPiece, row, col };
          console.log(`Selected ${clickedPiece} at (${row}, ${col})`);

        } else {
          console.log("Cannot select opponent's piece.");
        }
      } else {
         // Clicked on an empty square without a piece selected
         console.log("Clicked empty square.");
      }
    },
    isValidMove(piece, startRow, startCol, endRow, endCol) {
      // TODO: Implement chess move validation rules based on the piece type
      // This is a placeholder, replace with actual logic
      console.log("Validating move for piece:", piece);
      return true; // Assume all moves are valid for now
    },
    // Add more methods for move validation, check detection, etc.
  },
};
</script>

<style scoped>
.chess-game {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: sans-serif;
}

.chessboard {
  display: grid;
  grid-template-columns: repeat(8, 60px); /* 8 columns */
  grid-template-rows: repeat(8, 60px);    /* 8 rows */
  width: 480px; /* 8 * 60px */
  height: 480px; /* 8 * 60px */
  border: 2px solid #333;
  margin-bottom: 20px;
}

.chess-row {
  display: contents; /* Important for grid layout */
}

.chess-cell {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0d9b5; /* Light squares */
  cursor: pointer;
  position: relative; /* For potential highlighting or move indicators */
}

.chess-cell.dark {
  background-color: #b58863; /* Dark squares */
}

.piece {
  font-size: 40px; /* Adjust size as needed */
  line-height: 1;
  user-select: none; /* Prevent text selection */
}

.white-piece {
  color: #ffffff;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5); /* Add shadow for visibility */
}

.black-piece {
  color: #000000;
}

.status {
  text-align: center;
}

/* Add styles for selected piece, possible moves, etc. later */
.chess-cell.selected { /* Example style for selected square */
    outline: 3px solid yellow;
    outline-offset: -3px;
}

.selected-piece {
  background-color: rgba(255, 255, 0, 0.3); /* Example: Yellow highlight */
}
</style>